package org.activiti.app.conf.cas;

import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object principal = authentication.getPrincipal();
        if (authentication instanceof CasAuthenticationToken) {
            CasAuthenticationToken casAuthenticationToken = (CasAuthenticationToken) authentication;
            Assertion assertion = (casAuthenticationToken).getAssertion();
            logger.info(assertion.getPrincipal().getAttributes().toString());
        }
        if (principal instanceof UserDetails) {
            String username = ((UserDetails) principal).getUsername();
//            RemoteUser user = new RemoteUser();
//            user.setId(username);
//            user.setDisplayName(username);
//            FlowableAppUser flowableAppUser = new FlowableAppUser(user, username, new ArrayList<>());
//            logger.info("{} Authentication Success", username);
//            SecurityContextHolder.getContext().setAuthentication(new RememberMeAuthenticationToken(username,
//                    flowableAppUser, flowableAppUser.getAuthorities()));


        }
        super.onAuthenticationSuccess(request, response, authentication);
    }
}
